package com.zhi.syc.data_applist.services;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.zhi.syc.data_applist.beans.ASMediaInfoBean;
import com.zhi.syc.data_applist.logger.ASLogger;
import com.zhi.syc.data_applist.util.ASUtil;

import java.io.File;
import java.util.ArrayList;

public class ASMediaInfo {

    public static ASMediaInfoBean getMediaInfo(Context context) {
        ASMediaInfoBean mediaInfoBean = new ASMediaInfoBean();
        try {
            mediaInfoBean.setDownloadFiles(getDownloadFileCount(context));
            mediaInfoBean.setContactGroup(getContactGroupCount(context));

            ArrayList<String> audioExtFiles = getMediaAudioFilePaths(context, true);
            ArrayList<String> audioIntFiles = getMediaAudioFilePaths(context, false);
            ArrayList<String> imageExtFiles = getMediaImageFilePaths(context, true);
            ArrayList<String> imageIntFiles = getMediaImageFilePaths(context, false);
            ArrayList<String> videoExtFiles = getMediaVideoFilePaths(context, true);
            ArrayList<String> videoIntFiles = getMediaVideoFilePaths(context, false);

            mediaInfoBean.setAudioExternal(audioExtFiles.size() + "");
            mediaInfoBean.setAudioInternal(audioIntFiles.size() + "");
            mediaInfoBean.setImagesExternal(imageExtFiles.size() + "");
            mediaInfoBean.setImagesInternal(imageIntFiles.size() + "");
            mediaInfoBean.setVideoExternal(videoExtFiles.size() + "");
            mediaInfoBean.setVideoInternal(videoIntFiles.size() + "");

            audioExtFiles.clear();
            audioIntFiles = null;
            imageExtFiles.clear();
            imageIntFiles = null;
            videoExtFiles.clear();
            videoIntFiles = null;

        } catch (Exception e) {
            e.printStackTrace();
        }

        String DownloadFiles = ASUtil.safeString(mediaInfoBean.getDownloadFiles());
        mediaInfoBean.setDownloadFiles(DownloadFiles);

        String ContactGroup = ASUtil.safeString(mediaInfoBean.getContactGroup());
        mediaInfoBean.setContactGroup(ContactGroup);

        String AudioExternal = ASUtil.safeString(mediaInfoBean.getAudioExternal());
        mediaInfoBean.setAudioExternal(AudioExternal);

        String AudioInternal = ASUtil.safeString(mediaInfoBean.getAudioInternal());
        mediaInfoBean.setAudioInternal(AudioInternal);

        String ImagesExternal = ASUtil.safeString(mediaInfoBean.getImagesExternal());
        mediaInfoBean.setImagesExternal(ImagesExternal);

        String ImagesInternal = ASUtil.safeString(mediaInfoBean.getImagesInternal());
        mediaInfoBean.setImagesInternal(ImagesInternal);

        String VideoExternal = ASUtil.safeString(mediaInfoBean.getVideoExternal());
        mediaInfoBean.setVideoExternal(VideoExternal);

        String VideoInternal = ASUtil.safeString(mediaInfoBean.getVideoInternal());
        mediaInfoBean.setVideoInternal(VideoInternal);

        mediaInfoBean.setFetchMediaFilesTime(ASUtil.safeString(getFetchMediaFilesTime()));

        return mediaInfoBean;
    }

    public static String getDownloadDir(Context context) {
        String dir = "";
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            dir = Environment.getExternalStorageDirectory() + "/Download";
        } else {
            dir = context.getExternalFilesDir("Download").getAbsolutePath();
        }
        return dir;
    }

    public static String getDownloadsDir(Context context) {
        String dir = "";
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            dir = Environment.getExternalStorageDirectory() + "/Downloads";
        } else {
            dir = context.getExternalFilesDir("Downloads").getAbsolutePath();
        }
        return dir;
    }

    public static String getDownloadFileCount(Context context) {
        String countStr = "0";
        try {
            int count = 0;
            File downloadFile = new File(getDownloadDir(context));
            if (downloadFile.exists()) {
                File[] files = downloadFile.listFiles();
                if (null != files) {
                    count += files.length;
                }
            }

            File downloadsFile = new File(getDownloadsDir(context));
            if (downloadsFile.exists()) {
                File[] files = downloadsFile.listFiles();
                if (null != files) {
                    count += files.length;
                }
            }

            countStr = (count + "");

        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //ASLogger.d("ASMediaUtil", "getDownloadFileCount: " + countStr);

        return countStr;
    }

    public static String getContactGroupCount(Context context) {
        String countStr = "0";
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(ContactsContract.Groups.CONTENT_URI, null, null, null, null);
            int count = 0;
            while (cursor.moveToNext()) {
                count += 1;
                //int groupId = cursor.getInt(cursor.getColumnIndex(ContactsContract.Groups._ID)); // 组id
                //String groupName = cursor.getString(cursor.getColumnIndex(ContactsContract.Groups.TITLE)); // 组名
            }
            countStr = (count + "");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return countStr;
    }

    public static ArrayList<String> getMediaAudioFilePaths(Context context, boolean isExternal) {
        ArrayList<String> paths = new ArrayList<>();
        Cursor cursor = null;
        try {
            Uri mediaUri = MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
            if (isExternal) {
                mediaUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }
            cursor = context.getContentResolver().query(mediaUri, null, null, null, null);
            if (cursor == null) {
                return paths;
            }

            while (cursor.moveToNext()) {
                String filePath = cursor.getString(cursor.getColumnIndex("_data"));
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    int id = cursor.getColumnIndex("_id");
                    filePath = mediaUri.buildUpon().appendPath(String.valueOf(cursor.getInt(id))).build().toString();
                }
                if (false == TextUtils.isEmpty(filePath)) {
                    paths.add(filePath);
                }
                //ASLogger.d("ASMediaUtil", "getMediaAudioFilePaths: " + paths.toString());
            }

            if (false == cursor.isClosed()) {
                cursor.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        return paths;
    }

    public static ArrayList<String> getMediaVideoFilePaths(Context context, boolean isExternal) {
        ArrayList<String> paths = new ArrayList<>();
        Cursor cursor = null;
        try {
            Uri mediaUri = MediaStore.Video.Media.INTERNAL_CONTENT_URI;
            if (true == isExternal) {
                mediaUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            }
            cursor = context.getContentResolver().query(mediaUri, null, null, null, null);
            if (cursor == null) {
                return paths;
            }
            while (cursor.moveToNext()) {
                String filePath = cursor.getString(cursor.getColumnIndex("_data"));
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    int id = cursor.getColumnIndex("_id");
                    filePath = mediaUri.buildUpon().appendPath(String.valueOf(cursor.getInt(id))).build().toString();
                }

                if (!TextUtils.isEmpty(filePath)) {
                    paths.add(filePath);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        return paths;
    }

    public static ArrayList<String> getMediaImageFilePaths(Context context, boolean isExternal) {
        ArrayList<String> paths = new ArrayList<>();
        Cursor cursor = null;
        try {
            Uri mediaUri = MediaStore.Images.Media.INTERNAL_CONTENT_URI;
            if (isExternal) {
                mediaUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            }
            cursor = context.getContentResolver().query(mediaUri, null, null, null, null);
            if (cursor == null) {
                return paths;
            }
            while (cursor.moveToNext()) {
                String filePath = cursor.getString(cursor.getColumnIndex("_data"));
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    int id = cursor.getColumnIndex("_id");
                    filePath = mediaUri.buildUpon().appendPath(String.valueOf(cursor.getInt(id))).build().toString();
                }
                if (!TextUtils.isEmpty(filePath)) {
                    paths.add(filePath);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        return paths;
    }

    public static String getFetchMediaFilesTime() {
        return String.valueOf(System.currentTimeMillis());
    }

    public static String getListZipString(Context paramContext) {
        String zipString = "";
        try {
            ASMediaInfoBean mediaInfoBean = getMediaInfo(paramContext);
            String result = new Gson().toJson(mediaInfoBean).trim();
            ASLogger.d(ASMediaInfo.class.getSimpleName(), "result: " + result);
            zipString = ASUtil.stringToGZIP(result);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return zipString;
    }
}
